<template>
  <div>
    <img class="shadow-2" :src="qrcodeUrl" :width="width" :height="height" style="width:317px; height:400px " />
    <canvas id="qrcodecanvas" ref="qrcodecanvas" style="display: none;"></canvas>
  </div>
</template>

<script>
import { defineComponent } from 'vue';
import QRCode from 'qrcode';
import { mapState } from 'pinia';
import { useStore } from 'stores/store';

export default defineComponent({
  name: 'QrCode',
  props: {
    code: String,
    title: String,
    subTitle: String,
    width: {
      type: Number,
      default: 950
    },
    height: {
      type: Number,
      default: 1200
    }
  },
  data () {
    return {
      qrcodeUrl: '/images/default_img.jpg'
    };
  },
  mounted () {
    this.generateQR();
  },
  methods: {
    generateQR () {
      QRCode.toCanvas(this.code, { width: this.width }, (err, cvs) => {
        if (err) console.log(err);
        this.$nextTick(() => {
          const w = this.width, h = this.height;
          const canvas = document.getElementById('qrcodecanvas');
          const ctx = canvas.getContext('2d');
          const devicePixelRatio = window.devicePixelRatio || 1;
          const backingStoreRatio = ctx.webkitBackingStorePixelRatio || 1;
          const ratio = (devicePixelRatio / backingStoreRatio) * 2;
          canvas.width = w * ratio;
          canvas.height = h * ratio;
          canvas.style.width = w + 'px';
          canvas.style.height = h + 'px';
          ctx.scale(ratio, ratio);
          ctx.fillStyle = '#fff';
          ctx.fillRect(0, 0, w, h);
          ctx.drawImage(cvs, 0, 100); // qr位置
          ctx.fillStyle = '#000';
          ctx.textAlign = 'center';
          ctx.font = '48px 宋体';

          ctx.fillText(this.siteInfo.company || '', w / 2, 80);
          ctx.font = '60px 宋体';
          ctx.fillText(this.title, w / 2, 160);
          ctx.font = '48px 宋体';
          ctx.fillText(this.subTitle, w / 2, 1070);
          ctx.font = '24px 宋体';
          ctx.fillText('技术支持：浙江木多鱼智能科技有限公司', w / 2, 1150);
          ctx.fillText('电话：664828', w / 2, 1180);

          this.qrcodeUrl = canvas.toDataURL('image/png');
        });
      });
    }
  },
  watch: {
    code () {
      this.generateQR();
    },
    title () {
      this.generateQR();
    },
    subTitle () {
      this.generateQR();
    }
  },
  computed: {
    ...mapState(useStore, ['siteInfo'])
  }
});
</script>
